﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;
using Framework;

namespace Enterprise
{
    public class OrderService : BaseService
    {
        /// <summary>
        /// 根据ID获取一条记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataRow GetById(int id)
        {
            DataRowCollection rows =
                DbHelperOleDb.Query("select * from TbOrder where CoOrderId={0}".FormatWith(id)).Tables["ds"].Rows;
            return rows[0];
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public Table GetTable(int pageValue = 0, int rowsValue = 0, string sort = "CoDate", string order = "Desc",
                              string code = "")
        {
            var parameters = new[]
                {
                    new OleDbParameter("@CoCode", OleDbType.VarChar, 255)
                };
            parameters[0].Value = code.SqlLike();
            var sbSqlWhere = new StringBuilder();
            sbSqlWhere.Append(" where cocode like '%'+@CoCode+'%'  ");
            int total =
                DbHelperOleDb.GetSingle("select count(*) from tborder {0}".FormatWith(sbSqlWhere), parameters).SafeToInt
                    ();
            var sbSql = new StringBuilder();
            sbSql.AppendFormat("select top {0} * from tborder {1} ", rowsValue, sbSqlWhere);
            if (pageValue > 1)
                sbSql.AppendFormat(
                    " and coorderid not in (select top {0} coorderid from tborder {1} order by {2} {3},coorderid desc)  ",
                    rowsValue * (pageValue - 1), sbSqlWhere, sort, order);
            sbSql.AppendFormat(" order by {0} {1},coorderid desc ", sort, order);
            DataSet ds = DbHelperOleDb.Query(sbSql.ToString(), parameters);
            var table = new Table
                {
                    Rows = ds.Tables["ds"].Rows,
                    Total = total,
                    DataTable = ds.Tables["ds"]
                };
            return table;
        }
        public int Add(
            int memberId = 0,
            string code = "",
            Dictionary<int, int> goodsList = null,
            string buyerName = "",
            string mobile = "",
            string telephone = "",
            string email = "",
            string address = "",
            string payment = "",
            string receiptWay = "",
            string deliveryWay = "",
            string manifestNo = "",
            DateTime? date = null,
             DateTime? shipDate = null,
             DateTime? receiptDate = null,
             DateTime? completeDate = null,
            string consignee = "",
            bool isReceipt = false,
            bool isDelivery = false,
            bool isClose = false,
            bool isDelete = false,
            bool isComplete = false,
            double discount = 10,
            decimal goodsAmount = 0,
            decimal postage = 0,
            decimal totalAmoun = 0,
            decimal integral = 0)
        {
            var sbSql = new StringBuilder();
            sbSql.Append("insert into  TbOrder(");
            sbSql.Append("CoMemberId,CoCode,CoDate,CoTotalAmount,CoDiscount,CoAddress,CoMobile,CoTelephone,CoEmail,CoPayment,CoBuyerName,CoReceiptWay,CoDeliveryWay,CoIsReceipt,CoIsDelivery,CoGoodsAmount,CoPostage,CoManifestNo,CoShipDate,CoReceiptDate,CoConsignee,CoIsClose,CoIsDelete,ColsComplete,CoCompleteDate,CoIntegral");
            sbSql.Append(") values (");
            sbSql.Append("@CoMemberId,@CoCode,@CoDate,@CoTotalAmount,@CoDiscount,@CoAddress,@CoMobile,@CoTelephone,@CoEmail,@CoPayment,@CoBuyerName,@CoReceiptWay,@CoDeliveryWay,@CoIsReceipt,@CoIsDelivery,@CoGoodsAmount,@CoPostage,@CoManifestNo,@CoShipDate,@CoReceiptDate,@CoConsignee,@CoIsClose,@CoIsDelete,@ColsComplete,@CoCompleteDate,@CoIntegral");
            sbSql.Append(")");
            var parameters = new[]
                {
                    new OleDbParameter("@CoMemberId", OleDbType.Integer),
                    new OleDbParameter("@CoCode", OleDbType.VarChar,255),
                    new OleDbParameter("@CoDate", OleDbType.Date),
                    new OleDbParameter("@CoTotalAmount", OleDbType.Decimal),
                    new OleDbParameter("@CoDiscount", OleDbType.Double),
                    new OleDbParameter("@CoAddress", OleDbType.VarChar,255),
                    new OleDbParameter("@CoMobile", OleDbType.VarChar,255),
                    new OleDbParameter("@CoTelephone", OleDbType.VarChar,255),
                    new OleDbParameter("@CoEmail", OleDbType.VarChar,255),
                    new OleDbParameter("@CoPayment", OleDbType.VarChar,255),
                    new OleDbParameter("@CoBuyerName", OleDbType.VarChar,255),
                    new OleDbParameter("@CoReceiptWay", OleDbType.VarChar,255),
                    new OleDbParameter("@CoDeliveryWay", OleDbType.VarChar,255),
                    new OleDbParameter("@CoIsReceipt", OleDbType.Boolean),
                    new OleDbParameter("@CoIsDelivery", OleDbType.Boolean),
                    new OleDbParameter("@CoGoodsAmount", OleDbType.Decimal),
                    new OleDbParameter("@CoPostage", OleDbType.Decimal),
                    new OleDbParameter("@CoManifestNo", OleDbType.VarChar,255),
                    new OleDbParameter("@CoShipDate", OleDbType.Date),
                    new OleDbParameter("@CoReceiptDate", OleDbType.Date),
                    new OleDbParameter("@CoConsignee", OleDbType.VarChar,255),
                    new OleDbParameter("@CoIsClose", OleDbType.Boolean),
                    new OleDbParameter("@CoIsDelete", OleDbType.Boolean),
                    new OleDbParameter("@ColsComplete", OleDbType.Boolean),
                    new OleDbParameter("@CoCompleteDate", OleDbType.Date),
                    new OleDbParameter("@CoIntegral", OleDbType.Integer)
                };
            parameters[0].Value = memberId;
            parameters[1].Value = code;
            parameters[2].Value = date ?? DateTime.Now;
            parameters[3].Value = totalAmoun;
            parameters[4].Value = discount;
            parameters[5].Value = address;
            parameters[6].Value = mobile;
            parameters[7].Value = telephone;
            parameters[8].Value = email;
            parameters[9].Value = payment;
            parameters[10].Value = buyerName;
            parameters[11].Value = receiptWay;
            parameters[12].Value = deliveryWay;
            parameters[13].Value = isReceipt;
            parameters[14].Value = isDelivery;
            parameters[15].Value = goodsAmount;
            parameters[16].Value = postage;
            parameters[17].Value = manifestNo;
            parameters[18].Value = shipDate ?? DateTime.Now;
            parameters[19].Value = receiptDate ?? DateTime.Now;
            parameters[20].Value = consignee;
            parameters[21].Value = isClose;
            parameters[22].Value = isDelete;
            parameters[23].Value = isComplete;
            parameters[24].Value = completeDate ?? DateTime.Now;
            parameters[25].Value = integral;
            var newId = DbHelperOleDb.Add(sbSql.ToString(), parameters);
            var sqlList = new ArrayList();
            if (goodsList != null)
            {
                foreach (var item in goodsList)
                {
                    sqlList.Add("insert into tborderdetail(CoOrderId,CoUnitPrice,CoOriginalPrice,CoOrderPrice    ,CoMarketPrice,CoTotalAmount  ,CoDiscount,CoQuantity,CoGoodsId   ,CoGoodsName,CoIntegral,CoDate) " +
                                                  " select {0}      ,CoPrice*{1},CoPrice        ,CoPrice*{1}*{2} ,CoPrice      ,CoPrice*{1}*{2},{1}       ,{2}       ,CoProductId,CoName     ,{3}         ,t.codate      from tbproduct,(select codate from tborder where coorderid=1) as t where coproductid={5}".FormatWith(newId, 1, item.Value, 0, date ?? DateTime.Now, item.Key));
                }
                sqlList.Add("update tborder E set E.CoGoodsAmount=B.TotalAmount,E.CoTotalAmount=(E.CoPostage+B.TotalAmount),E.CoDiscount={0} from (select sum(d.CoOrderPrice) TotalAmount from TbOrderDetail d where d.coorderid={1})  B".FormatWith(1, newId));
            }
            DbHelperOleDb.ExecuteSqlTran(sqlList);
            return newId;
        }

        public int Edit(
             int orderId = 0,
             int memberId = 0,
             string code = "",
             Dictionary<int, int> goodsList = null,
             string buyerName = "",
             string mobile = "",
             string telephone = "",
             string email = "",
             string address = "",
             string payment = "",
             string receiptWay = "",
             string deliveryWay = "",
             string manifestNo = "",
             DateTime date = default(DateTime),
             DateTime shipDate = default(DateTime),
             DateTime receiptDate = default(DateTime),
             DateTime completeDate = default(DateTime),
             string consignee = "",
             bool isReceipt = false,
             bool isDelivery = false,
             bool isClose = false,
             bool isDelete = false,
             bool isComplete = false,
             double discount = 10,
             decimal goodsAmount = 0,
             decimal postage = 0,
             decimal totalAmoun = 0,
             decimal integral = 0)
        {
            return 0;
        }

        public void Delete(int id)
        {
            DbHelperOleDb.ExecuteSqlTran(new ArrayList
                {
                    "delete from TbOrderDetail where CoOrderId={0}".FormatWith(id),
                    "delete from TbOrder where CoOrderId={0}".FormatWith(id)
                });
        }
    }
}